const path = require("path")
const conn = require("../model/index")
var md5 = require('md5');
const { secret } = require("../config")

const otr = require('../uilt/path')

this.login = (req, res) => {
    url = path.resolve(__dirname, "../views/login.html")
    res.sendFile(url)
}

this.registry = (req, res) => {
    let { username, password } = req.body
    let sql = `SELECT  * from  userinfo WHERE  name=?`
    conn(sql, [username]).then((result) => {
        if (result.length == 0) {
            password = md5(password + secret)
            //  成功就插入数据库 
            let sql = `INSERT userinfo(name,password) VALUES( ? , ? )`
            conn(sql, [username, password]).then(() => {
                res.json({
                    code: 20000,
                    message: "注册成功"
                })
            })
        } else {
            res.json({
                code: "40002",
                message: "用户名已被占用"
            })
        }
    })

}
this.index = (req, res) => {
    res.sendFile(path.resolve(__dirname, "../views/index.html"))
}
this.tologin = (req, res) => {
    let { username, password } = req.body
    password = md5(password + secret)  // 密码提前转化 为加密后的结果

    var sql = `SELECT  * from  userinfo WHERE  name=? and password =?`
    conn(sql, [username, password]).then((result) => {
        if (result.length == 1) {
            req.session.userinfo = result[0]
            res.json({
                code: 20000,
                message: "登录成功"
            })
        } else {
            res.json({
                code: 40001,
                message: "登录失败"
            })
        }
    })

}

this.ore = async (req, res) => {
    let { page, size } = req.body

    page = (page - 1) * size
    let sql = 'SELECT * FROM userinfo WHERE STATUS = 0 LIMIT ?,? '
    let result = await conn(sql, [page, size])
    res.json({
        message: 200,
        data: result
    })

}

this.add = async (req, res) => {
    let result = otr.path(req.file)
    let { name, password, sex, class: class1 } = req.body
    password = md5(password + secret)

    let sql = `INSERT userinfo(name,password,sex,class,avatar) VALUES(?,?,?,?,?)`
    await conn(sql, [name, password, sex, class1, result])
    res.json({
        message: 2000
    })

}


this.del = async (req, res) => {
    let { id } = req.body
    let sql = 'UPDATE userinfo SET status=1 WHERE id = ?'
    conn(sql, [id])
    res.json({
        message: 2000
    })
}

this.xgai = async (req, res) => {
    let result = null
    if (req.file) {
        result = otr.path(req.file)
    }

    let { name, password, sex, class: class1, id } = req.body
    password = md5(password + secret)

    let sql = `UPDATE userinfo SET name=?,password=?,sex=?,class=?,avatar=? WHERE id = ?`

    await conn(sql, [name, password, sex, class1, result, id])

    res.json({
        message: 2000
    })


}